package com.ruoyi.web.controller.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.entity.BO.SmsSendBO;
import com.ruoyi.common.utils.lianlu.LianluSmsUtils;
import com.ruoyi.web.controller.member.mapper.IBackMemberMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/back/lianLuSms")
public class BackLianLuSmsController extends BaseController {

    @Resource
    private LianluSmsUtils lianluSmsUtils;

    @Resource
    private IBackMemberMapper backMemberMapper;


    @PostMapping("/searchTemplateList")
    @ResponseBody
    public TableDataInfo searchTemplateList() {
        ArrayList<JSONObject> list = new ArrayList<>();
        TableDataInfo result = new TableDataInfo();
        result.setMsg("查询成功！");
        try {
            JSONObject response = lianluSmsUtils.querySmsTemplateList(false);
            if(response.containsKey("message") && response.getString("message").equals("success")){
                List<JSONObject> tmpList = JSONObject.parseArray(response.getString("data"),JSONObject.class);
                tmpList.forEach(x -> {
                    if (x.getString("status").equals("1")) {
                        list.add(x);
                    }
                });
            }
            result.setRows(list);
            result.setTotal(list.size());
        } catch (Exception e) {
            //
            result.setTotal(0);
            result.setRows(list);
        }
        return result;
    }

    @PostMapping("/send")
    @ResponseBody
    public AjaxResult send(SmsSendBO smsSendBO) {
        try {
            List<String> phoneList = backMemberMapper.searchPhoneList(smsSendBO.getMemberIdStr());
            if (!phoneList.isEmpty()) {
                smsSendBO.setNotify(false);
                smsSendBO.setPhoneNumberArr(phoneList.toArray(new String[0]));
                JSONObject response = LianluSmsUtils.templateSend(smsSendBO);
                if(response.containsKey("message") && response.getString("message").equals("success")){
                    return AjaxResult.success("发送成功");
                }else{
                    return AjaxResult.error("发送失败！");
                }
            } else {
                return AjaxResult.error("请选择已手机授权的会员！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送失败");
        }
    }
}
